import React, {useEffect, useState} from 'react'
import {Button, Upload, Row, Col, Steps, message, Modal} from 'antd'
import styles from './index.less'
import {getTemplateUrl} from '@/service/common/download'
import CustomTable from '@/components/Table'
// 图标
import {IconFont} from '@/utils/common/tool'
// api调用
import {getErrorList} from '@/service/carMessage/accident'

const {Step} = Steps
type PropsType = {
	title?: string // 弹框标题
	isModalOpen: boolean // 弹框是否可见
	setIsModalOpen: React.Dispatch<React.SetStateAction<boolean>>
	setFileObj?: React.Dispatch<any>
	importData: () => void // 导入保存方法
	downloadUrl?: string // 下载模板url
	uploadFileUrl?: string // 上传模板url
	fileData?: any
	fileNmae?: string
	columns: any
	kid?: string
	sourceId?: number
	templateType?: string
}

const batchUpload = (props: PropsType) => {
	const {
		title = '批量导入',
		isModalOpen,
		setIsModalOpen,
		setFileObj,
		importData,
		uploadFileUrl,
		fileData,
		fileNmae,
		columns,
		kid = 'id',
		sourceId,
		templateType,
	} = props
	const [current, setCurrent] = useState(0)
	const [show, setShow] = useState(true)
	const [errorList, setErrorList] = useState<any>([])
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [successTotal, setSuccessTotal] = useState(0)
	const [errorTotal, setErrorTotal] = useState(0)
	const [loading, setLoading] = useState(false)

	const getTable = async () => {
		setLoading(true)
		getErrorList(params).then((res: any) => {
			if (res?.success) {
				setTotal(res?.data?.total)
				setErrorList(res?.data?.records)
				setLoading(false)
			}
			return {}
		})
	}
	// 页码变化更新导入失败表格数据
	useEffect(() => {
		if (current === 1 || current === 2) {
			getTable()
		}
	}, [params, current])

	// 批量处理提交
	const onBatchSubmit = async () => {
		if (current < 2) {
			setCurrent(current + 1)
		} else if (current === 2) {
			setShow(true)
			setCurrent(() => 0)
			importData()
		}
	}
	const uploadProps = {
		action: uploadFileUrl,
		name: fileNmae,
		data: fileData,
		beforeUpload: (file: any) => {
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.error('文件必须小于200MB')
			}
			return isLt200M
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				message.success('上传成功')
				setFileObj?.(info?.file?.originFileObj)
				setSuccessTotal(() => info?.file?.response?.data?.successCount)
				setErrorTotal(() => info?.file?.response?.data?.failCount)
				setShow(false)
			}
			if (info.file.status === 'error') {
				setShow(false)
				message.error(info?.file?.response.msg)
			}
		},
		onDrop() {},
		onRemove(info: any) {
			setShow(true)
			message.success(`${info?.name}移除成功`)
		},
	}
	const onCancel = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
		setShow(true)
		setCurrent(0)
		setIsModalOpen(false)
	}
	const onBack = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
		setShow(true)
		setCurrent(0)
		if (current === 0 || current === 2) {
			setIsModalOpen(false)
		} else {
			setCurrent(current - 1)
		}
	}
	return (
		<Modal
			title={title}
			open={isModalOpen}
			onCancel={() => {
				onCancel()
			}}
			width={700}
			destroyOnClose
			footer={
				<>
					<Button size="small" onClick={onBack}>
						{current === 0 ? '取消' : '上一步'}
					</Button>
					<Button
						type="primary"
						size="small"
						onClick={onBatchSubmit}
						disabled={show}>
						{current === 2 ? '保存' : '下一步'}
					</Button>
				</>
			}>
			<div className={styles.batchUpload}>
				<Row gutter={12}>
					<Col sm={{span: 22, offset: 1}}>
						<Steps current={current} labelPlacement="vertical">
							<Step title="下载模板、上传文件" />
							<Step title="文件导入、数据检测" />
							<Step title="确认结果、完成导入" />
						</Steps>
					</Col>
				</Row>
				{current >= 1 ? (
					<Row gutter={12}>
						<Col sm={{span: 24}}>
							<div className="error">
								已成功{successTotal}条,失败{errorTotal}条
							</div>
						</Col>
						<Col sm={{span: 24}}>
							<div className="customTable">
								<CustomTable
									params={params}
									columns={columns}
									pagination
									total={total}
									kid={kid}
									scroll={{y: 300}}
									callback={(pagination: any) => {
										setParams(pagination)
									}}
									loading={loading}
									dataSource={errorList}
								/>
							</div>
						</Col>
					</Row>
				) : (
					<Row gutter={12}>
						<Col sm={{span: 24}}>
							<div className="stepBox">
								<div className="inlineImg">
									<IconFont type="icon-xiazai" />
								</div>
								<div className="inlineText">
									<div className="inlineContent">
										<div className="text title">
											下载文件模板、填写导入信息
										</div>
										<Button
											type="primary"
											shape="round"
											size="small"
											className="downOrupload"
											onClick={() =>
												getTemplateUrl(
													sourceId,
													templateType,
												)
											}>
											下载模板
										</Button>
									</div>
								</div>
							</div>
						</Col>
						<Col sm={{span: 24}}>
							<div className="stepBox">
								<div className="inlineImg">
									<IconFont type="icon-a-shangchuan1" />
								</div>
								<div className="inlineText">
									<div className="inlineContent">
										<div className="text title">
											上传导入模板
										</div>
										<div className="text">
											支持文件xls、xlsx（即Excel表格），文件大小不得超过200M，最大支持导入50万条数据
										</div>
									</div>

									<>
										<Upload {...uploadProps}>
											{!show ? (
												''
											) : (
												<Button
													type="primary"
													shape="round"
													size="small"
													className="downOrupload">
													文件上传
												</Button>
											)}
										</Upload>
									</>
								</div>
							</div>
						</Col>
					</Row>
				)}
			</div>
		</Modal>
	)
}
export default batchUpload
